//
//  ToolClass.m
//  YunYuZhiJia
//
//  Created by 苏荷 on 14/12/3.
//  Copyright (c) 2014年 苏荷. All rights reserved.
//

#import "ToolClass.h"
@implementation ToolClass


+ (BOOL)isFirstOpenApp:(NSString *)key
{
    if(![[NSUserDefaults standardUserDefaults] boolForKey:key])
    {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:key];
        return YES;
    }
    else{
        return NO;
    }
    return NO;
}
/**
 * 根据View返回VC
 *
 **/
+ (UIImage *)scaleToSize:(UIImage *)originImage
{
    float width = originImage.size.width;
    float height = originImage.size.height;
    
    if (width>640) {
        height = 640*height/width;
        width = 640;
        
        UIGraphicsBeginImageContext(CGSizeMake(width, height));
        [originImage drawInRect:CGRectMake(0,0, width, height)];
        // 从当前context中创建一个改变大小后的图片
        UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
        // 使当前的context出堆栈
        UIGraphicsEndImageContext();
        //返回新的改变大小后的图片
        return scaledImage;
    }
    else{
        return originImage;
    }
    
}

+ (void)showAlertTitle:(NSString *)title Message:(NSString *)message
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:title message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}


//获取用户id
+ (NSString * )getUserId
{
    NSDictionary *user = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_info"];
    NSString *userID = [user objectForKey:@"id"];
    if (!userID) {
        userID = @"";
    }
    return userID;
}


+ (UIViewController*)viewController:(UIView *)view {
    for (UIView* next = [view superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}

+(AppDelegate *)appdelegate
{
    return (AppDelegate *)[[UIApplication sharedApplication]delegate];
}

//判断是否是有效的邮箱
+(BOOL)isValidateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}



//保存历史记录
+ (void)saveHistory:(NSMutableArray *)arr{
    [[NSUserDefaults standardUserDefaults] setObject:arr forKey:@"history"];
}
+ (NSMutableArray *)getHistory{
    NSMutableArray *arr = [[NSUserDefaults standardUserDefaults] objectForKey:@"history"] ;
    return arr;
}

//获取随机验证码
+ (NSString *)getVerificationCode
{
    NSArray *strArr = [[NSArray alloc]initWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",nil] ;
    NSMutableString *getStr = [[NSMutableString alloc]initWithCapacity:5];
    for(int i = 0; i < 6; i++) //得到六位随机字符,可自己设长度
    {
        int index = arc4random() % ([strArr count]);  //得到数组中随机数的下标
        [getStr appendString:[strArr objectAtIndex:index]];
        
    }
    NSLog(@"验证码:%@",getStr);
    return getStr;
}
+ (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (unsigned int)strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}


//判断合法的电话号码
+ (BOOL)checkTel:(NSString *)str
{
    
    if ([str length] == 0) {
        return NO;
    }
    NSString *regex =@"^((1[0-9][0-9])|(1[0-9][0-9])|(1[0-9][^4,\\D])|(1[0-9][0,5-9]))\\d{8}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:str];
    if (!isMatch) {
        return NO;
    }
    return YES;
    
}
//判断输入是否为空格
+(BOOL)isEmpty:(NSString *) str {
    if (!str) {
        return YES;
    } else {
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        
        if ([trimedString length] == 0) {
            return YES;
        } else {
            return NO;
        }
    }
}



//提示成功提问 成功收藏 成功点赞
+ (void)tipAnimationWith:(NSString *)title
{
    UIWindow * win = [UIApplication sharedApplication].keyWindow;
    UILabel *likeLable;
    if (likeLable == nil) {
        UILabel *likeLable=[[UILabel alloc]init];
        likeLable.backgroundColor=[UIColor blackColor];
        likeLable.layer.cornerRadius = 5;
        likeLable.layer.masksToBounds = YES;
        likeLable.alpha=0.8;
        likeLable.textAlignment=NSTextAlignmentCenter;
        likeLable.font=[UIFont systemFontOfSize:12];
        likeLable.text=title;
        CGRect rect =[title boundingRectWithSize:CGSizeMake(1000, 30) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12]} context:nil];
        likeLable.bounds = CGRectMake(0, 0, rect.size.width + 20, 30);
        //[likeLable sizeToFit];
        likeLable.center = CGPointMake(Main_Screen_Width/2, Main_Screen_Height-150);
        
        likeLable.textColor=[UIColor whiteColor];
        
        [UIView animateWithDuration:2 animations:^{
            //            likeLable.center = CGPointMake(SCREEN_WIDTH/2, SCREEN_HEIGHT-80);
            likeLable.alpha = 1;
        } completion:^(BOOL finished)
         {
             [UIView animateWithDuration:1 animations:^{
                 [likeLable removeFromSuperview];
             }];
         }];
        
        [win addSubview:likeLable];
    }
    
}



//判断是否为整形数字
+ (BOOL)isPureInt:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}
    
//判断字符串>8位“字符”
+ (BOOL)isValidateName:(NSString *)name{
    NSUInteger  character = 0;
    for(int i=0; i< [name length];i++){
        int a = [name characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff){ //判断是否为中文
            character +=2;
        }else{
            character +=1;
        }
    }
    
    if (character >=8) {
        return YES;
    }else{
        return NO;
    }
    
}

+(NSString *)urlencode:(NSString *) str
{
    NSMutableString *output = [NSMutableString string];
    const unsigned char *source = (const unsigned char *)[str UTF8String];
    unsigned long sourceLen = strlen((const char *)source);
    for (int i = 0; i < sourceLen; ++i) {
        const unsigned char thisChar = source[i];
        if (thisChar == ' '){
            [output appendString:@"+"];
        } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
                   (thisChar >= 'a' && thisChar <= 'z') ||
                   (thisChar >= 'A' && thisChar <= 'Z') ||
                   (thisChar >= '0' && thisChar <= '9')) {
            [output appendFormat:@"%c", thisChar];
        } else {
            [output appendFormat:@"%%%02X", thisChar];
        }
    }
    return output;
}
//解析 图片宽高
+ (NSDictionary *)pictureWidthAndHeight:(NSString *)str
{
    NSData * data = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary * result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    return  result;
    
}
//压缩图片
+ (UIImage *)imageWithMaxSide:(CGFloat)length sourceImage:(UIImage *)image
{
    CGFloat scale = [[UIScreen mainScreen] scale];
    CGSize imgSize = CWSizeReduce(image.size, length);
    UIImage *img = nil;
    
    UIGraphicsBeginImageContextWithOptions(imgSize, YES, scale);  // 创建一个 bitmap context
    
    [image drawInRect:CGRectMake(0, 0, imgSize.width, imgSize.height)
            blendMode:kCGBlendModeNormal alpha:1.0];              // 将图片绘制到当前的 context 上
    
    img = UIGraphicsGetImageFromCurrentImageContext();            // 从当前 context 中获取刚绘制的图片
    UIGraphicsEndImageContext();
    
    return img;
}
static inline
CGSize CWSizeReduce(CGSize size, CGFloat limit)   // 按比例减少尺寸
{
    CGFloat max = MAX(size.width, size.height);
    if (max < limit) {
        return size;
    }
    
    CGSize imgSize;
    CGFloat ratio = size.height / size.width;
    
    if (size.width > size.height) {
        imgSize = CGSizeMake(limit, limit*ratio);
    } else {
        imgSize = CGSizeMake(limit/ratio, limit);
    }
    
    return imgSize;
}


+(NSString *)number:(float) price
{
    NSString *priceStr = [NSString stringWithFormat:@"%.1f",price];
    if (priceStr.length>=9) {
        return [NSString stringWithFormat:@"%@万",[priceStr substringToIndex:priceStr.length-6]];
    }
    return priceStr;
}

+(int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
    NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
    NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
    NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
    NSComparisonResult result = [dateA compare:dateB];
    NSLog(@"date1 : %@, date2 : %@", oneDay, anotherDay);
    if (result == NSOrderedDescending) {
        //NSLog(@"Date1  is in the future");
        return 1;
    }
    else if (result == NSOrderedAscending){
        //NSLog(@"Date1 is in the past");
        return -1;
    }
    //NSLog(@"Both dates are the same");
    return 0;
    
}



// 根据颜色16进制数值得到UIColor
+ (UIColor *)colorFromHexRGB:(NSString *)inColorString{
    UIColor *result = nil;
    unsigned int colorCode = 0;
    unsigned char redByte, greenByte, blueByte;
    
    if (nil != inColorString)
    {
        NSScanner *scanner = [NSScanner scannerWithString:inColorString];
        (void) [scanner scanHexInt:&colorCode]; // ignore error
    }
    redByte = (unsigned char) (colorCode >> 16);
    greenByte = (unsigned char) (colorCode >> 8);
    blueByte = (unsigned char) (colorCode); // masks off high bits
    result = [UIColor
              colorWithRed: (float)redByte / 0xff
              green: (float)greenByte/ 0xff
              blue: (float)blueByte / 0xff
              alpha:1.0];
    return result;
}

//判断字符串是否为空
+ (BOOL) isBlankString:(NSString *)string {
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    return NO;
}
    
#pragma mark--计算字数
+ (int)countWord:(NSString*)s

{
    int i,n=(int)[s length],l=0,a=0,b=0;
    
    unichar c;
    
    for(i=0;i<n;i++){
        
        c=[s characterAtIndex:i];
        
        if(isblank(c)){
            
            b++;
            
        }else if(isascii(c)){
            
            a++;
            
        }else{
            
            l++;
        }
        
    }
    

    if(a==0 && l==0) return 0;
    
    return l+(int)ceilf((float)(a+b)/2.0);

}

//判断是否为字典类型
+(BOOL)isBlankDic:(NSDictionary *)dic{

    if ([dic isKindOfClass:[NSDictionary class]]) {
        return YES;
    }else{
        return NO;
    }

}

+ (void)putShadowOnView:(UIView *)view Radius:(CGFloat)radius Color:(CGColorRef)color ShadowRadius:(CGFloat)sRadius Opacity:(float)opacity
{
    view.layer.cornerRadius = radius;
    view.layer.shadowColor = color;//shadowColor阴影颜色
    view.layer.shadowOffset = CGSizeMake(0,0);//shadowOffset阴影偏移,x向右偏移4，y向下偏移4，默认(0, -3),这个跟shadowRadius配合使用
    view.layer.shadowOpacity = opacity;//阴影透明度，默认0
    view.layer.shadowRadius = sRadius;//阴影半径，默认3
}
+ (void)bigShowMessage:(NSString *)message
{
    UIWindow * win = [[[UIApplication sharedApplication] delegate] window];
    UIView *coverView;
    if (coverView == nil) {
        UIView *coverView = [[UIView alloc]initWithFrame:win.bounds];
        coverView.backgroundColor = [UIColor blackColor];
        coverView.alpha = 0.5;
        [win addSubview:coverView];
        
        UILabel *likeLable=[[UILabel alloc]init];
        likeLable.backgroundColor=[UIColor whiteColor];
        likeLable.layer.cornerRadius = 10;
        likeLable.layer.masksToBounds = YES;
        likeLable.alpha=0.95;
        likeLable.textAlignment=NSTextAlignmentCenter;
        likeLable.font=[UIFont systemFontOfSize:15];
        likeLable.text=message;
        likeLable.bounds = CGRectMake(0, 0, Main_Screen_Width-120, 150);
        likeLable.center = CGPointMake(Main_Screen_Width/2, 300);
        likeLable.textColor=[UIColor grayColor];
        likeLable.numberOfLines = 0;
        [win addSubview:likeLable];
        
        [UIView animateWithDuration:2 animations:^{
            likeLable.alpha = 1;
        } completion:^(BOOL finished)
         {
             [UIView animateWithDuration:1 animations:^{
                 [likeLable removeFromSuperview];
                 [coverView removeFromSuperview];
             }];
         }];
    }
}

//用颜色来生成图片
+(UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;

}
+ (CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize String:(NSString *)string{
    NSDictionary *attr = @{NSFontAttributeName:font};
    return [string boundingRectWithSize:maxSize
                                options:NSStringDrawingUsesLineFragmentOrigin attributes:attr context:nil].size;
}

//时间字符自定义
+(NSString *)dateformatter:(NSString *)dateStr{

    NSString *dateString = dateStr;
    //设置转换格式
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //NSString转NSDate
    NSDate *date=[formatter dateFromString:dateString];
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    [outputFormatter setLocale:[NSLocale currentLocale]];
    [outputFormatter setDateFormat:@"yyyy/MM/dd"];
    NSString *str = [outputFormatter stringFromDate:date];
    return str;
}


//手机号中间用****代替
+(NSString *)numberSuitScanf:(NSString*)number{

    NSString *numberString = [number stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    return numberString;
}

+ (NSString *)weekdayStringFromDate:(NSString *)inputDate {
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy.MM.dd"];
    NSDate *date =[dateFormat dateFromString:inputDate];
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"Sunday", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    [calendar setTimeZone: timeZone];
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:date];
    return [weekdays objectAtIndex:theComponents.weekday];
}

+ (NSString *)stringFromDate:(NSDate *)currentDate formate:(NSString *)formatStr{
    //用于格式化NSDate对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设置格式：zzz表示时区
//    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
    [dateFormatter setDateFormat:formatStr];
    //NSDate转NSString
    NSString *currentDateString = [dateFormatter stringFromDate:currentDate];
    //输出currentDateString    NSLog(@"%@",currentDateString);
    return currentDateString;

}

//NSString转NSDate
+ (NSDate *)dateFromString:(NSString *)dateString formate:(NSString *)formatStr{
    //设置转换格式
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateFormat:formatStr];
    //NSString转NSDate
    NSDate *date=[formatter dateFromString:dateString];
    return date;
}

// 时间戳转时间
+ (NSString *)getDateStringWithTimeStr:(NSString *)str formate:(NSString *)formatStr{
    NSTimeInterval time=[str doubleValue];
    NSDate *detailDate=[NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:formatStr];
    NSString *currentDateStr = [dateFormatter stringFromDate: detailDate];
    return currentDateStr;
}
//时间字符自定义
+(NSString *)dateformatter:(NSString *)dateStr formattor:(NSString *)formattor {
    
    NSString *dateString = dateStr;
    //设置转换格式
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //NSString转NSDate
    NSDate *date=[formatter dateFromString:dateString];
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    [outputFormatter setLocale:[NSLocale currentLocale]];
    [outputFormatter setDateFormat:formattor];
    NSString *str = [outputFormatter stringFromDate:date];
    return str;
}


//获取当前周时间段
+(NSString *)getWeekTime{
    NSDate *date=[NSDate date];
    NSMutableArray *dataArr = [NSMutableArray array];
    
    for (int i = 0; i < 52; i++) {
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDateComponents *comp = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday|NSCalendarUnitDay
                                             fromDate:date];
        NSInteger weekDay = [comp weekday];
        NSInteger day = [comp day];
        
        long firstDiff,lastDiff;
        if (weekDay == 1) {
            firstDiff = 0;
            lastDiff = 7;
        }else{
            firstDiff = [calendar firstWeekday] - weekDay  + 1;
            lastDiff = 8 - weekDay;
        }
        
        NSDateComponents *firstDayComp = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date];
        [firstDayComp setDay:day + firstDiff];
        NSDate *firstDayOfWeek= [calendar dateFromComponents:firstDayComp];
        
        NSDateComponents *lastDayComp = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date];
        [lastDayComp setDay:day + lastDiff];
        NSDate *lastDayOfWeek= [calendar dateFromComponents:lastDayComp];
        
        NSDateFormatter *formater = [[NSDateFormatter alloc] init];
        [formater setDateFormat:@"yyyy.MM.dd"];
        
        NSString *str1 = [formater stringFromDate:firstDayOfWeek];
        NSString *str2 = [formater stringFromDate:lastDayOfWeek];
        NSString *weekStr = [NSString stringWithFormat:@"%@~%@",str1,str2];
        
        [dataArr addObject:weekStr];
        
        NSDateComponents *tempComp = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date];
        [tempComp setDay:day - 7];
        NSDate  *tempDate =  [calendar dateFromComponents:tempComp];
        
        date = tempDate;
    }
    
    return dataArr[1];

}

//获取昨天年月
+(NSString *)getYearAndMonth{
    return  [ToolClass stringFromDate:[NSDate dateWithTimeIntervalSinceNow:-(24*60*60*30)] formate:@"YYYY-MM"];
}

//获取当前年
+(int)getYear{
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate* dt = [NSDate date];
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitWeekday;
    NSDateComponents *comp = [gregorian components: unitFlags
                                          fromDate:dt];
    return (int)comp.year;
}

//判读身份证号正确
+(BOOL)CheckIsIdentityCard: (NSString *)identityCard{
    //判断是否为空
    if (identityCard==nil||identityCard.length <= 0) {
        return NO;
    }
    //判断是否是18位，末尾是否是x
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    if(![identityCardPredicate evaluateWithObject:identityCard]){
        return NO;
    }
    //判断生日是否合法
    NSRange range = NSMakeRange(6,8);
    NSString *datestr = [identityCard substringWithRange:range];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat : @"yyyyMMdd"];
    if([formatter dateFromString:datestr]==nil){
        return NO;
    }
    
    //判断校验位
    if(identityCard.length==18)
    {
        NSArray *idCardWi= @[ @"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2" ]; //将前17位加权因子保存在数组里
        NSArray * idCardY=@[ @"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2" ]; //这是除以11后，可能产生的11位余数、验证码，也保存成数组
        int idCardWiSum=0; //用来保存前17位各自乖以加权因子后的总和
        for(int i=0;i<17;i++){
            idCardWiSum+=[[identityCard substringWithRange:NSMakeRange(i,1)] intValue]*[idCardWi[i] intValue];
        }
        
        int idCardMod=idCardWiSum%11;//计算出校验码所在数组的位置
        NSString *idCardLast=[identityCard substringWithRange:NSMakeRange(17,1)];//得到最后一位身份证号码
        
        //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
        if(idCardMod==2){
            if([idCardLast isEqualToString:@"X"]||[idCardLast isEqualToString:@"x"]){
                return YES;
            }else{
                return NO;
            }
        }else{
            //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
            if([idCardLast intValue]==[idCardY[idCardMod] intValue]){
                return YES;
            }else{
                return NO;
            }
        }
    }
    return NO;
}

+(UICollectionViewFlowLayout *)setUICollectionViewFlowLayout:(UICollectionViewFlowLayout *)flow Width:(float) width High:(float) high
                                                 minHspacing:(float) minhs minVspacing:(float) minvs UiedgeUp:(float) up Uiedgeleft:(float) left Uiedgebottom:(float)bottom Uiedgeright:(float)right Scdirection:(BOOL) direction{
    flow = [UICollectionViewFlowLayout new];
    //格子的大小 (长，高)
    flow.itemSize = CGSizeMake(width, high);
    //横向最小距离
    flow.minimumInteritemSpacing = minhs;
    //代表的是纵向的空间间隔
    flow.minimumLineSpacing=minvs;
    //设置，上／左／下／右 边距 空间间隔数是多少
    flow.sectionInset = UIEdgeInsetsMake(up, left, bottom, right);
    
    //确定是水平滚动，还是垂直滚动
    if (direction) {
        [flow setScrollDirection:UICollectionViewScrollDirectionVertical];
    }else{
        [flow setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    }
    return flow;
}

//自定义搜索框
+(UISearchBar *)customerSearchBar{
    UISearchBar *searchBar=[[UISearchBar alloc]init];
    searchBar.backgroundColor=[UIColor clearColor];
    searchBar.showsCancelButton=NO;
    searchBar.tintColor=[UIColor grayColor];
    searchBar.placeholder=@"搜索";
    for (UIView *subView in searchBar.subviews) { if ([subView isKindOfClass:[UIView class]]) { [[subView.subviews objectAtIndex:0] removeFromSuperview]; if ([[subView.subviews objectAtIndex:0] isKindOfClass:[UITextField class]]) {
        UITextField *textField = [subView.subviews objectAtIndex:0];
        textField.backgroundColor = [UIColor whiteColor]; //设置输入框边框的颜色 //
        textField.layer.borderColor = [UIColor whiteColor].CGColor; //
        textField.layer.borderWidth = 1;
        textField.textColor = [UIColor lightGrayColor]; //设置默认文字颜色
        UIColor *color = [UIColor grayColor];
        textField.font=SYSTEMFONT(12);
        [textField setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"搜索" attributes:@{NSForegroundColorAttributeName:color}]]; //修改默认的放大镜图片
       // UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 13, 13)]; imageView.backgroundColor = [UIColor clearColor]; imageView.image = [UIImage imageNamed:@"gww_search_ misplaces"];
        //textField.leftView = imageView;
    }
    }
    }
        
    return searchBar;
    
}

+(NSString *)stringformat:(NSString *)str{
    NSDate *timeData = [NSDate dateWithTimeIntervalSince1970:[str doubleValue]];
    NSDateFormatter *dateFormatter =[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy.MM.dd"];
    NSString *strTime = [dateFormatter stringFromDate:timeData];
    return strTime;
}


//JSON格式的字符串
+(id)dictionaryWithJsonString:(NSString *)jsonString{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingAllowFragments
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return jsonObject;
}


//设置阴影
+(void)setShadow:(UIView *)view color:(UIColor *)color{
    view.layer.shadowOffset=CGSizeMake(0, 0);
    view.layer.shadowRadius=3;
    view.layer.cornerRadius=2;
    view.layer.shadowOpacity=0.5;
    view.layer.shadowColor=color.CGColor;
}


//判断输入是否包含表情
+ (BOOL)isContainsTwoEmoji:(NSString *)string{
    __block BOOL isEomji = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         const unichar hs = [substring characterAtIndex:0];
         //         NSLog(@"hs++++++++%04x",hs);
         if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f)
                 {
                     isEomji = YES;
                 }
                 //                 NSLog(@"uc++++++++%04x",uc);
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3|| ls ==0xfe0f) {
                 isEomji = YES;
             }
             //             NSLog(@"ls++++++++%04x",ls);
         } else {
             if (0x2100 <= hs && hs <= 0x27ff && hs != 0x263b) {
                 isEomji = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 isEomji = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 isEomji = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 isEomji = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50|| hs == 0x231a ) {
                 isEomji = YES;
             }
         }
         
     }];
    return isEomji;
}

@end
